'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const topN = event.top || 5;

  // 获取本月起始和下月起始日期字符串
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const nextMonth = month === 12 ? 1 : month + 1;
  const nextMonthYear = month === 12 ? year + 1 : year;

  const pad = (n) => (n < 10 ? '0' + n : n);
  const monthStart = `${year}-${pad(month)}-01`;
  const nextMonthStart = `${nextMonthYear}-${pad(nextMonth)}-01`;

  try {
    // Step 1: 聚合统计本月每位咨询师的咨询次数
    const aggRes = await db.collection('appoint_records')
      .aggregate()
      .match({
        day: _.gte(monthStart).and(_.lt(nextMonthStart))
      })
      .group({
        _id: '$consultant',
        count: { $sum: 1 }
      })
      .sort({
        count: -1
      })
      .limit(topN)
      .end();

    const topConsultantsStats = aggRes.data;
    const consultantIds = topConsultantsStats.map(item => item._id);

    // Step 2: 查询 consultants 表，获取 name 和 avatar
    const consultantInfoRes = await db.collection('consultants')
      .where({
        user_id: _.in(consultantIds)
      })
      .get();

    const consultantInfoMap = {};
    consultantInfoRes.data.forEach(con => {
      consultantInfoMap[con.user_id] = {
        name: con.name || '未知',
        avatar: con.avatar || ''
      };
    });

    // Step 3: 合并数据
    const result = topConsultantsStats.map(item => {
      const info = consultantInfoMap[item._id] || {};
      return {
        name: info.name,
        avatar: info.avatar,
        count: item.count
      };
    });

    return {
      success: true,
      result
    };

  } catch (err) {
    console.error('获取咨询师排行失败:', err);
    return {
      success: false,
      message: '获取咨询师排行失败',
      error: err.message
    };
  }
};
